const jwt = require('jsonwebtoken');

const verifyToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];

  if (!authHeader) {
    console.log('未提供 Authorization header');
    return res.status(403).send({ message: '未提供token' });
  }

  const token = authHeader.replace('Bearer ', '');

  try {
    const decoded = jwt.verify(
      token,
      process.env.JWT_SECRET || 'your-secret-key'
    );
    req.user = decoded;
    next();
  } catch (err) {
    console.error('Token验证错误:', {
      error: err.message,
      stack: err.stack,
      token: token,
      headers: req.headers,
    });
    return res.status(401).send({ message: '无效的token' });
  }
};

const isAdmin = (req, res, next) => {
  if (req.user && req.user.role === 'admin') {
    next();
  } else {
    res.status(403).send({ message: '需要管理员权限' });
  }
};

const isNurse = (req, res, next) => {
  if (req.user && (req.user.role === 'nurse' || req.user.role === 'admin')) {
    next();
  } else {
    res.status(403).send({ message: '需要护士权限' });
  }
};

module.exports = {
  verifyToken,
  isAdmin,
  isNurse,
};
